package com.wywah.core.locators;

import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * 动态加载路由信息， 可基于数据库、redis等途经保存路由信息
 * @see org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator
 * @see org.springframework.cloud.gateway.route.CachingRouteLocator 主要看这个
 * @see org.springframework.cloud.gateway.route.InMemoryRouteDefinitionRepository
 * @see org.springframework.cloud.gateway.route.RedisRouteDefinitionRepository
 */
@Configuration
public class DynamicRouteLocator implements RouteDefinitionLocator {

    private final ApplicationEventPublisher publisher;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> routes = new ArrayList<>();
        RouteDefinition routeDefinition = new RouteDefinition();
        routeDefinition.setId("test");
        routeDefinition.setUri(URI.create("lb://test1"));
        List<PredicateDefinition> predicates = new ArrayList<>();
        PredicateDefinition predicateDefinition = new PredicateDefinition("Path=/api/test/**");
        predicates.add(predicateDefinition);
        routeDefinition.setPredicates(predicates);
        List<FilterDefinition> filters = new ArrayList<>();

        FilterDefinition filterDefinition = new FilterDefinition("RewritePath=/api/test/?(?<segment>.*), /$\\{segment}");
        filters.add(filterDefinition);

        FilterDefinition filterDefinitio2n = new FilterDefinition();
        filterDefinitio2n.setName("Log");
        filters.add(filterDefinitio2n);
        routeDefinition.setFilters(filters);
        routes.add(routeDefinition);
        System.out.println("获取路由信息");
        return Flux.fromIterable(routes);
    }

    public DynamicRouteLocator(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }
}
